﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Rabbit.API.Application.Command.Goods;
using Rabbit.API.DTOs;

namespace Rabbit.API.Application.Handler.Goods
{
    /// <summary>
    /// 获取商品信息列表
    /// </summary>
    public class GoodsGetHandler : IRequestHandler<GoodsGetCommand, APIPaging<GoodsDTO>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly IMapper mapper;
        private readonly ILogger<GoodsGetHandler> log;

        public GoodsGetHandler(IRepository<GoodsModel> goodsway, IMapper mapper, ILogger<GoodsGetHandler> log)
        {
            this.goodsway = goodsway;
            this.mapper = mapper;
            this.log = log;
        }
        /// <summary>
        /// 获取商品信息列表
        /// </summary>
        /// <param name="request">分页</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>获取商品信息列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIPaging<GoodsDTO>> Handle(GoodsGetCommand request, CancellationToken cancellationToken)
        {
            APIPaging<GoodsDTO> res = new APIPaging<GoodsDTO>();
            try
            {
                
                var goods = goodsway.GetAll().Where(x => x.IsDel == false);
                if (!string.IsNullOrEmpty(request.GoodsName))  //商品名称
                {
                    goods = goods.Where(x => x.GoodsName.Contains(request.GoodsName));
                }
                if (!string.IsNullOrEmpty(request.CreateBatch))  //生产批次
                {
                    goods = goods.Where(x => x.CreateBatch == request.CreateBatch);
                }
                if (!string.IsNullOrEmpty(request.CreateCode))  //生产许可证号
                {
                    goods = goods.Where(x => x.CreateCode == request.CreateCode);
                }
                if (request.ExpireTime != null)  //保质期
                {
                    goods = goods.Where(x => x.ExpireTime == request.ExpireTime);
                }
                if (!string.IsNullOrEmpty(request.CreateCompany))  //公司名称
                {
                    goods = goods.Where(x => x.CreateCompany.Contains(request.CreateCompany));
                }
                var result = mapper.Map<List<GoodsDTO>>(goods);
                res.Totalcount = result.Count();
                res.Num = StateCode.OK;
                res.DataPage = result.OrderBy(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
                res.Message = $"获取商品信息列表成功";

            }
            catch (Exception ex)
            {
                log.LogError($"发生异常{ex.Message}");
            }
            return Task.FromResult(res);


        }
    }
}
